import { useMemo, useState, useEffect, createContext } from 'react';
import { Table, Switch, Button, Form } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { uuid } from '@inbiz/utils';
import Color from '@inbiz/basic/Color';
import { EditableRow, EditableCell } from './EditCell';
import { defaultUserTaskActions, defaultCtSignTaskActions, defaultFirstTaskActions, buttonTableActionsEnum } from '../../utils';
import './style.less';

interface DataType {
    id: string;
    buttton: string;
    name: string;
    enable: boolean;
};

const OpButtonEditableContext = createContext<any>(null);
export { OpButtonEditableContext };

export default function ButtonTable(props: any) {
    const { value, onChange, type } = props;
    const [curId, setCurId] = useState<string>('');
    const [form] = Form.useForm();

    useEffect(() => {
        if (!value) {
            if(type == 'firstTask'){
                onChange(defaultFirstTaskActions);
            };
            if (type == 'userTask') {
                onChange(defaultUserTaskActions);
            };
            if (type == 'ctSignTask') {
                onChange(defaultCtSignTaskActions);
            };
        };
    }, [value, type]);

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const onSwitchChange = (row: DataType) => {
        const _value = value?.map((item: { id: string, enable: boolean }) => {
            if (item?.id == row?.id) {
                return {
                    ...item,
                    enable: !item?.enable,
                };
            } else {
                return item;
            };
        });
        onChange(_value);
    };

    const onColorChange = (type: string, id: string, rgb: string) => {
        const _value = value?.map((item: { id: string; }) => {
            if (item?.id == id) {
                return {
                    ...item,
                    [type]: rgb
                }
            } else {
                return item
            }
        });
        onChange(_value);
    };

    const addCustomButton = () => {
        let _value = value ? [...value] : [];
        _value.push({
            id: 'button' + uuid(20, 60),
            action: 'custom',
            name: '自定义按钮',
            type: 'custom',
            bgColor: 'rgba(25,137,250,1)',
            fontColor: 'rgba(255,255,255,1)',
            enable: true,
        });
        onChange(_value);
    };

    const deleteCustomButton = (id: string) => {
        const _value = value?.filter((item: { id: string }) => item?.id != id);
        onChange(_value);
    };

    const handleSave = (row: any) => {
        const newData: any = [...value];
        const index = newData.findIndex((item: { id: string }) => row.id === item.id);
        const item: any = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        onChange(newData);
    };

    const defaultColumns = [
        {
            title: '操作按钮',
            dataIndex: 'action',
            key: 'action',
            width: '17%',
            ellipsis: true,
            tooltip: true,
            render: (t: string) => buttonTableActionsEnum?.[t] || '',
        },
        {
            title: '显示名称',
            dataIndex: 'name',
            key: 'name',
            editable: true,
            width: '20%',
            ellipsis: true,
        },
        {
            title: '标识',
            dataIndex: 'type',
            key: 'type',
            editable: true,
            width: '20.6%',
            ellipsis: true,
        },
        {
            title: '背景颜色',
            dataIndex: 'bgColor',
            key: 'bgColor',
            width: '15%',
            ellipsis: true,
            render: (t: string, r: any) => {
                return <Color value={t} onChange={(value: string) => { onColorChange('bgColor', r?.id, value) }} />
            },
        },
        {
            title: '字体颜色',
            dataIndex: 'fontColor',
            key: 'fontColor',
            width: '15%',
            ellipsis: true,
            render: (t: string, r: any) => {
                return <Color value={t} onChange={(value: string) => { onColorChange('fontColor', r?.id, value) }} style={{ right: 125 }} />
            },
        },
        {
            title: '启用',
            dataIndex: 'enable',
            key: 'enable',
            width: '11.4%',
            render: (t: boolean, r: any) => {
                if (r?.type == 'custom') {
                    return <a style={{ color: 'var(--inbiz-color-danger)' }} onClick={() => { deleteCustomButton(r?.id) }}>删除</a>
                } else {
                    return (
                        <Switch defaultChecked={t} onChange={() => { onSwitchChange(r) }} />
                    )
                };
            },
        },
    ];

    const columns: any = useMemo(() => {
        return defaultColumns.map((col: any) => {
            if (!col.editable) {
                return col;
            };
            return {
                ...col,
                onCell: (record: any) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    required: col.required,
                    variateId: curId,
                    setNowKey: (e: any) => setCurId(e),
                    handleSave,
                }),
            };
        })
    }, [curId, defaultColumns]);

    return (
        <div className='process-designer-operation-button-table-wrapper'>
            <Form form={form}>
                <OpButtonEditableContext.Provider value={form}>
                    <Table
                        columns={columns}
                        components={components}
                        dataSource={value}
                        pagination={false}
                        size='small'
                        rowKey="id"
                        bordered
                        rowClassName={'process-designer-operation-button-table-row'}
                        footer={type == 'plusSignButton' ? undefined : () => {
                            return <Button icon={<PlusOutlined />} size='small' onClick={addCustomButton}>添加自定义按钮</Button>;
                        }}
                    />
                </OpButtonEditableContext.Provider>
            </Form>
        </div>
    )
}